<template>
  <div class="mg-content">
    <div class="table-search text-left" >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-select style="width:100%" v-model="cateSearch" filterable placeholder="请选择商品类别" size="medium">
            <el-option
              v-for="item in selectCateList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input v-model="input" @keyup.enter.native="keyDown($event)" placeholder="请输入名称或快捷码" :maxlength="20"  size="medium"></el-input>
        </el-col>
        <el-col :span="8">
          <el-button  class="btn-info"  icon="el-icon-search" @click="search"  size="medium">搜索</el-button>
          <el-button  class="btn-warning" style="margin-left: 1px"  icon="el-icon-refresh" @click="cleanSearch"  size="medium">重置</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-padding">
      <div class="title-buttons">
      <!--  <router-link to="/dishesMessage/add" v-hasPermission="'management_dishes:edit'">
          <el-button  class="title-button btn-primary" icon="el-icon-plus" size="medium">新建&nbsp;</el-button>
        </router-link>-->
        <el-button v-hasPermission="'management_dishes:edit'"  class="title-button btn-primary" @click="add()" icon="el-icon-plus" size="medium">新建&nbsp;</el-button>
        <el-button  class="title-button btn-primary" @click="addParam=true;" >附加属性&nbsp;</el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        :border="true"
        style="width: 100%">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          label="编号"
          width="80"
        >
          <template scope="scope">
            <span>{{scope.row.no}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="名称">
          <template scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="200"
          label="类别">
          <template scope="scope">
            <span>{{scope.row.category.name}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="storeType=='ZC' || storeType=='KC'"
          label="规格">
          <template scope="scope">
            <span v-if="scope.row.specificationRelations && scope.row.specificationRelations[0].specName" v-for="i in scope.row.specificationRelations">{{i.specName}},</span>
            <span v-else>----</span>
          </template>
        </el-table-column>
        <el-table-column v-if="storeType=='ZC' || storeType=='KC' || storeType=='HB'"
          label="做法">
          <template scope="scope">
            <span v-if="scope.row.makeRelations.length>0" >   <span v-for="i in scope.row.makeRelations">{{i.name}},</span></span>
            <span v-else>----</span>
          </template>
        </el-table-column>
        <el-table-column v-if="storeType=='ZC' || storeType=='KC' || storeType=='HB'"
          label="加料">
          <template scope="scope">
            <span v-if="scope.row.feedRelations.length>0">    <span  v-for="i in scope.row.feedRelations">{{i.name}},</span></span>
            <span v-else>----</span>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          label="单位">
          <template scope="scope">
            <span>{{scope.row.unit}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="称重/时价">
          <template scope="scope">
            <span v-if="scope.row.weigh"><span class="right_green">√</span></span>
            <span v-else><span class="wrong_red">×</span></span>
            /
            <span v-if="scope.row.season"><span class="right_green">√</span></span>
            <span v-else><span class="wrong_red">×</span></span>
          </template>
        </el-table-column>

        <el-table-column
          width="100"
          label="商品价格">
          <template scope="scope">
            <span>{{scope.row.price | money}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          label="会员价格">
          <template scope="scope">
            <span>{{scope.row.vipPrice | money}}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="创建时间">
          <template scope="scope">
            <span>{{scope.row.createAt}}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="操作" width="120">
          <template slot-scope="scope" >
              <el-button v-hasPermission="'management_dishes:edit'" type="text" size="small" style="margin: 0px;" @click="goUpdate(scope.row.id)" >修改 | </el-button>
              <el-button  v-hasPermission="'management_dishes:edit'" type="text" size="small" style="margin: 0px;" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <br>
      <div class="block">
        <el-row>
          <el-col :span="24" class="text-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="pageSizes"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-------------表单窗口------------------>
    <model :isShow="addShow" :id="activityId" v-on:close="addClose" v-on:addSuccess="addSuccess"></model>
    <!-------------多规格窗口------------------>
    <el-dialog
      title="编辑商品信息"
      :visible.sync="dialogVisible"
      :before-close="handleClose" >
      <br>
      <div v-if="!acitiveDishe.weigh">
        <el-row style="width: 800px">
          <el-col  :span="8">
            <el-input  v-model="acitiveDishe.name" :disabled="true">
              <template slot="prepend">商品名称</template>
            </el-input><br><br>
            <span style="font-size: 16px">状态：</span>
            <el-checkbox v-model="isSuccess">是否启用</el-checkbox>
          </el-col>
          <el-col  :span="8" :offset="3">
            <el-input  v-model="acitiveDishe.price" :disabled="true">
              <template slot="prepend">价格</template>
            </el-input>
          </el-col>
        </el-row>
        <br>
        <div class="orderTable" v-if="isSuccess">
          <el-table
            :data="specificationsTableData"
            border
            style="width: 100%">
            <el-table-column
              type="index"
              width="50">
            </el-table-column>
            <el-table-column
              width="80">
              <template scope="scope">
                <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addSpecifColumn(scope.$index)"></span>
                <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusSpecifColumn(scope.$index)"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="dishesSpecification"
              label="规格">
              <template scope="scope">
                <div style="position: relative">
                  <el-select v-model.number="scope.row.specificationsId" style="width: 100%" @change="changeGuige(scope.$index)">
                    <el-option
                      v-for="item in dishesSpecificationList"
                      :key="item.id"
                      :label="item.name"
                      :disabled="item.state.key!='NORMAL'"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="money"
              label="单价">
              <template scope="scope">
                <el-input v-model="scope.row.money" @blur="moneyJiaoyan(scope.row,'money')"  placeholder="0.00"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="vipMoney"
              label="会员价">
              <template scope="scope">
                <el-input v-model="scope.row.vipMoney" @blur="vipMoneyJiaoyan(scope.row,'vipMoney')"  placeholder="0.00"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="isDefault"
              label="默认（是/否）">
              <template scope="scope" >
                <el-switch
                  v-model="scope.row.isDefault"
                  on-color="#13ce66"
                  on-text="是"
                  @change="defaultChange(scope.$index)"
                  off-text="否"
                  off-color="#ff4949">
                </el-switch>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <span style="    font-size: 14px;color: #888;padding: 0 12px;">（选择默认规格，此规格价格会作为商品默认价格显示在收银端与微餐厅界面）</span>
        <div style="clear: both"></div>
        <div class="el-dialog__footer">
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSpec">确 定</el-button>
              </span>
        </div>

      </div>
      <div v-else>
        当前商品为称重商品，不可配置规格
        <br>
        <br>
        <br>
        <br>
        <br>
      </div>
    </el-dialog>
    <!-------------多做法窗口------------------>
    <el-dialog
      title="编辑商品信息"
      v-model="dialogZuofa"
      :before-close="handleClose" >
      <br>
      <el-row style="width: 800px">
        <el-col  :span="8">
          <el-input  v-model="acitiveDishe.name" :disabled="true">
            <template slot="prepend">商品名称</template>
          </el-input><br><br>
          <span style="font-size: 16px">状态：</span>
          <el-checkbox v-model="isSuccess">是否启用</el-checkbox>
        </el-col>
        <el-col  :span="8" :offset="3">
          <el-input  v-model="acitiveDishe.price" :disabled="true">
            <template slot="prepend">价格</template>
          </el-input>
        </el-col>
      </el-row>
      <br>
      <div class="orderTable" v-if="isSuccess">
        <el-table
          :data="zuofaTableData"
          border
          style="width: 100%">
          <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            width="80">
            <template scope="scope">
              <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addColumn(scope.$index)"></span>
              <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusColumn(scope.$index)"></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="practiceId"
            label="做法">
            <template scope="scope">
              <div style="position: relative">
                <el-select v-model.number="scope.row.practiceId" style="width: 100%" @change="changeZuoFa(scope.$index)">
                  <el-option
                    v-for="item in dishesPracticeList"
                    :key="item.id"
                    :label="item.name"
                    :disabled="item.state.key!='NORMAL'"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="premiumRate"
            label="加价比例">
            <template scope="scope">
              <div style="position: relative">
                <el-select v-model.number="scope.row.premiumRate" style="width: 100%"  @change="premiumRateChange(scope.row)">
                  <el-option
                    v-for="item in priceupTypes"
                    :key="item.key"
                    :label="item.text"
                    :value="item.key">
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="money"
            label="比例/金额">
            <template scope="scope">
              <!--{{scope.row.money}}-->
              <el-input v-if="scope.row.premiumRate!='DONOTADD'" v-model="scope.row.money" @blur="isDouble(scope.row,'money')"  placeholder="0.00"></el-input>
              <label v-if="scope.row.premiumRate=='PROPROTIONADD'" style="position: absolute;z-index: 5;right: 10px;top: 0px;" >%</label>
              <label v-if="scope.row.premiumRate=='DONOTADD'">0.00</label>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--<span style="    font-size: 14px;color: #888;padding: 0 12px;">（选择默认规格，此规格价格会作为商品默认价格显示在收银端与微餐厅界面）</span>-->

      <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogZuofa = false">取 消</el-button>
                    <el-button type="primary" @click="submitPrem">确 定</el-button>
                  </span>
    </el-dialog>
    <el-dialog class="delete_dialog"
      title="提示"
      :visible.sync="dialogIsShow"
      width="30%"
      :before-close="handleClose">
      <br />
      <span v-if="branchs">当前商品在<span class="c-1">{{branchs}}</span>中已下发，删除后将删除单店中对应的商品信息</span>
      <span v-else>确定删除商品信息吗？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogIsShow = false">取 消</el-button>
    <el-button type="primary" @click="dialogResult">确 定</el-button>
  </span>
    </el-dialog>
    <addParamModel :isShow="addParam" v-on:close="addParamClose" v-on:addSuccess="addParamSuccess"></addParamModel>
  </div>
</template>
<script>
  //注意路径
  import model from './model.vue'
  import addParamModel from './addParamModel.vue'

  export default{
    data(){
      return {
        addParam:false,
        tableData: [],
        dialogIsShow:false,
        loading:false,
        pageSizes:window.pageSizes,
        pageSize:window.pageSize,
        currentPage:1,
        input:"",
        inputValue:"",
        total:0,
        addShow:false,
        activityId:"",
        acitiveDishe:{},
        dialogVisible:false,
        dishesSpecificationList:[],
        specificationsTableData:[
          {
            specificationsId: '',
            money: '0.00',
            vipMoney: '0.00',
            isDefault:false,
          }
        ],
        dialogZuofa:false,
        dishesPracticeList:[],
        zuofaTableData: [{
          practiceId: '',
          premiumRate: 'DONOTADD',
          money: '0.00',
        }],
        priceupTypes:[],
        isSuccess:true,
        cateSearch:"",
        selectCateList:[],
        flag:false,

        curDataRow:null,
        curDataIndex:0,
        selectItmeIndex:"",
        selectItemDetailsIndex:"",
        selectDelId:"",
        storeId:window.localStorage.getItem("dishKuId"),
        storeType: window.localStorage.getItem("dishKuType"),
        branchs:""
      }
    },
    components: {
      model,
      addParamModel
    },
    created(){
      window.this = this;
      this.inputValue="";
      this.initData();
    },
    methods: {
      addParamClose(){
        this.addParam=false;
      },
      addParamSuccess(){
        this.addParam=false;
      },
      add(){
        this.router.push({path:'/dishesMessage/add'});
      },
      goUpdate(id){
        console.log("dddddddddd");
        this.router.push({path:"/dishesMessage/add",query:{id:id}});
      },
      initData(){
        this.loading=true;
        this.currentPage=1;
        this.getData();
      },
      keyDown(ev){
        if(ev.keyCode==13) {
          this.currentPage=1;
          this.inputValue=this.input;
          this.getData();
        }
      },
      search(){
        this.currentPage=1;
        this.inputValue=this.input;
        this.getData();
      },
      cleanSearch(){
        this.currentPage=1;
        this.input="";
        this.inputValue=this.input;
        this.cateSearch="";
        this.getData();
      },
      handleCurrentChange(currentPage){
        this.currentPage=currentPage;
        this.getData();
      },
      getData(){
        this.$axios.get("dishes/dishess?page.pn="+this.currentPage+"&page.size="+this.pageSize+"&search.name_like,spell_like="+this.inputValue+"&search.category.id_eq="+this.cateSearch+"&storeId="+this.storeId).then((data)=>{
          if(data.status==200){
            this.loading=false
            this.tableData=data.content.dishesPage.content
            this.total=data.content.dishesPage.totalElements;
            this.selectCateList=data.content.categoryList;

          }else{
            this.loading=false
          }
        })
      },
      /*用户选择提示框后处理*/
      dialogResult(param){
        this.dialogIsShow=false;
        this.$axios.delete("dishes/dishess/"+this.curDataRow.id).then(data=>{
          if(data.status==200){
            this.tableData.splice(this.curDataIndex,1);
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData();
          }else{
            this.$message({
              type: 'error',
              message: data.message
            });
          }
        })
      },
      handleDelete(index, row) {
        console.log("dddddddddd");
        this.curDataIndex = index;
        this.curDataRow = row;
        this.dialogIsShow = true;
        this.branchs='';
        this.$axios.get("dishes/dishess/getDishesBranchs",{id:this.curDataRow.id}).then(data=>{
          if(data.status==200){
            if(data.content.branchs && data.content.branchs.length>0){
              for(var i=0;i<data.content.branchs.length;i++){
                this.branchs +=data.content.branchs[i].branch_name+",";
              }
              this.branchs = this.branchs.substring(0,this.branchs.length-1);
            }
            console.log(this.branchs);
          }
        })


//        return false;

      },
      handleClose(){
        this.dialogIsShow = false;

      },
      handleSelectionChange(){

      },
      addSuccess(item){
        this.addShow=false;
        this.currentPage=1;
        this.initData();
      },
      addClose(){
        this.addShow=false;
        this.initData();
      },
      handleSizeChange(val){
        this.pageSize=val;
        this.search();
      },
      dialogVisibleShow(item){
        item.isState=true;
        this.acitiveDishe=item;
        this.$http.get("dishess/findAllpecifications?id="+item.id).then(function(data){
          this.dishesSpecificationList=data.body.content.dishesSpecificationList;
          this.specificationsTableData=data.body.content.table
          if(!this.specificationsTableData || this.specificationsTableData.length<=0){
            this.specificationsTableData=[
              {
                specificationsId: '',
                money: '0.00',
                vipMoney: '0.00',
                isDefault:false,
              }
            ];
          }
        });
        this.dialogVisible=true;
      },
      submitSpec(){
        var data={};
        if(this.isSuccess){
          var defaultCount=0;
          for(var i=0;i<this.specificationsTableData.length;i++){
            if(this.specificationsTableData[i].isDefault && this.specificationsTableData[i].specificationsId){
              defaultCount++;
            }
          }
          if(defaultCount<=0){
            this.$message.error("请在多规格中选择一个默认值");
            return
          }
          if(!this.specificationsTableData[0].specificationsId){
            this.$message.error("商品规格第一行不能为空");
            return
          }
          data.dishesSpecifications=this.specificationsTableData;
        }
        data=JSON.stringify(data);
        this.$http.put("dishess/"+this.acitiveDishe.id+"/updateSpecifications",data,{'content-type': 'application/json'}).then(function(data){
          if(data.body.status==200){
            this.dialogVisible=false;
            this.getData();
            this.$message({
              message:data.body.message,
              type: 'success'
            });
          }else{
            this.$message.error(data.body.message);
          }
        });
      },
      submitPrem(){
        var data={};
        if(this.isSuccess){
          if(!this.zuofaTableData[0].practiceId){
            this.$message.error("商品规格第一行不能为空");
            return
          }
          data.dishesPractices=this.zuofaTableData;
        }
        data=JSON.stringify(data);
        this.$http.put("dishess/"+this.acitiveDishe.id+"/updatePecif",data,{'content-type': 'application/json'}).then(function(data){
          if(data.body.status==200){
            this.dialogZuofa=false;
            this.getData();
            this.$message({
              message:data.body.message,
              type: 'success'
            });
          }else{
            this.$message.error(data.body.message);
          }
        });
      },
      dialogZuofaShow(item){
        this.zuofaTableData=[];
        this.acitiveDishe=item;
        this.acitiveDishe.isState=true;
        this.$http.get("dishess/findAllDishesMakeRelation?id="+item.id).then(function(data){
          this.dishesPracticeList=data.body.content.dishesPracticeList;
          this.zuofaTableData=data.body.content.tableData;
          this.priceupTypes=data.body.content.priceupTypes;

          if(!this.zuofaTableData || this.zuofaTableData.length<=0){
            this.zuofaTableData=[{
              practiceId: '',
              premiumRate: 'DONOTADD',
              money: '0.00',
            }];
          }

          this.flag=!this.flag;
        });
        this.dialogZuofa=true;
      },
      //多规格 加列
      addSpecifColumn(index){
        this.specificationsTableData.splice(index+1,0,{
          specificationsId: '',
          money: '0.00',
          vipMoney: '0.00',
          isDefault:false,
        })
      },
      minusSpecifColumn(index){
        if(this.specificationsTableData.length>1){
          this.specificationsTableData.splice(index,1);
        }else{
          this.$message.info("最少保留一条");
        }
      },
      //多做法 加列
      addColumn(index){
        this.zuofaTableData.splice(index+1,0,{
          practiceId: '',
          premiumRate: 'DONOTADD',
          money:'0.00',
        })
      },
      minusColumn(index){
        if(this.zuofaTableData.length>1){
          this.zuofaTableData.splice(index,1);
        }else{
          this.$message.info("最少保留一条");
        }
      },
      changeGuige(index){
        for(var i=0;i<this.specificationsTableData.length;i++){
          if(i!=index && this.specificationsTableData[i].specificationsId==this.specificationsTableData[index].specificationsId){
            this.$message.error("不能选择重复规格");
            this.specificationsTableData[index].specificationsId=""
          }
        }
      },
      moneyJiaoyan(item,key){
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if(!isNum.test(item[key])){
          item[key]="0.00"
        }else{
          item[key]=item[key]
        }
        item["vipMoney"]=item[key];
      },
      vipMoneyJiaoyan(item,key){
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if(!isNum.test(item[key])){
          console.log("11111111")
          item[key]="0.00"
        }else if(item[key]>item["money"]){
          console.log("222222222")
          item[key]=item["money"]
        }else{
          console.log("44444")
          item[key]=item[key]
        }
      },
      defaultChange(index){
        for(var i=0;i<this.specificationsTableData.length;i++){
          this.specificationsTableData[i].isDefault=false;
        }
        this.specificationsTableData[index].isDefault=true;
        console.log(this.specificationsTableData[index]);
        var item=this.specificationsTableData[index];
        this.specificationsTableData.splice(index,1);
        this.specificationsTableData.splice(index,0,item);
      },
      isDouble(item,key){
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if( ! isNum.test(item[key])){
          item[key]="0.00"
        }else{
          item[key]=item[key]
        }
      },
      premiumRateChange(item){
        if(item.premiumRate!='DONOTADD' && item.money<=0){
          item.money=1;
        }
      },
      changeZuoFa(index){
        for(var i=0;i<this.zuofaTableData.length;i++){
          if(i!=index && this.zuofaTableData[i].practiceId==this.zuofaTableData[index].practiceId){
            this.$message.error("不能选择重复做法");
            this.zuofaTableData[index].practiceId=""
          }
        }
        for(let i=0;i<this.dishesPracticeList.length;i++){

          if(this.dishesPracticeList[i].id==this.zuofaTableData[index].practiceId){
            if(this.dishesPracticeList[i]){
              this.zuofaTableData[index].premiumRate=this.dishesPracticeList[i].priceupType.key;
              this.zuofaTableData[index].money = this.dishesPracticeList[i].priceupValue;
            }
          }
        }
      },
      changeState(){
        this.acitiveDishe.isState=false;
      }
    }
  }
</script>
<style scoped>
  .right_green{
    color: green;
    font-weight: bold;
  }
  .wrong_red{
    font-weight: bold;
  }
</style>
